#include "widget.h"
#include "ui_widget.h"

#include <QMessageBox>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    TcpServer = new QTcpServer(this);
    this->setWindowTitle("服务端");

    // 处理客户端的新连接
    connect(TcpServer,&QTcpServer::newConnection,this,&Widget::proessConnection);

    // 绑定端口，监听
    if(!TcpServer->listen(QHostAddress::Any,8080))
    {
        // 弹出错误对话框
        QMessageBox::critical(this,"服务器启动失败",TcpServer->errorString());
        return;
    }
}

Widget::~Widget()
{
    delete ui;
}

void Widget::proessConnection()
{
    // 获取新客户端对应的socket
    QTcpSocket *ClientSocket = TcpServer->nextPendingConnection();

    QString log = "[" + ClientSocket->peerAddress().toString() + ":" + QString::number(ClientSocket->peerPort()) + "]" + "新的客户端到了";

    ui->listWidget->addItem(log);

    // 处理客户端发来的请求
    connect(ClientSocket,&QTcpSocket::readyRead,[=](){
        // 获取客户端发来的请求
        QString str = ClientSocket->readAll();
        // 处理请求
        const QString respon = proess(str);
        // 响应回客户端
        ClientSocket->write(respon.toUtf8());

        QString log = "[" + ClientSocket->peerAddress().toString() + ":" + QString::number(ClientSocket->peerPort()) + "]" + "res: " + str
                      + "resp: " + respon;
        ui->listWidget->addItem(log);
    });

    // 处理客户端断开连接
    connect(ClientSocket,&QTcpSocket::disconnected,[=](){
        QString log = "[" + ClientSocket->peerAddress().toString() + ":" + QString::number(ClientSocket->peerPort()) + "]" + "客户端断开连接";
        ui->listWidget->addItem(log);
        // 回收
        ClientSocket->deleteLater();
    });
}

QString Widget::proess(QString &str)
{
    return str;
}

